﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Common.Helpers/ExcelHelper 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       ExcelHelper
* 创建时间：  2025/5/22 16:06:24
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using MySqlX.XDevAPI.Relational;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Utilities.Collections;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Common.Helpers
{
    public class ExcelHelper
    {
        #region 导出

        /// <summary>
        /// 生成Excel文档
        /// </summary>
        /// <returns></returns>
        public static MemoryStream BuildExcelDocument(DataSet dataSet)
        {
            MemoryStream ms = new MemoryStream();
            //创建Excel
            var workbook = new HSSFWorkbook();
            //循环Table
            for (int i = 0; i < dataSet.Tables.Count; i++)
            {
                DataTable dt = dataSet.Tables[i];
                var sheet = workbook.CreateSheet(dt.TableName);

                //设置表头
                int colIndex = 0;
                var headRow = sheet.CreateRow(0);
                headRow.HeightInPoints = 24;
                foreach (DataColumn col in dt.Columns)
                {
                    headRow.CreateCell(colIndex).SetCellValue(col.ColumnName);
                    colIndex++;
                }

                //设置起始行和列
                int rowIndex = 1;
                //导入数据
                foreach (DataRow row in dt.Rows)
                {
                    colIndex = 0;
                    var dataRow = sheet.CreateRow(rowIndex);
                    dataRow.HeightInPoints = 24;
                    foreach (DataColumn col in dt.Columns)
                    {
                        dataRow.CreateCell(colIndex).SetCellValue(row[col.ColumnName].ToString());
                        colIndex++;
                    }
                    rowIndex++;
                }
            }
            workbook.Write(ms);
            return ms;
        }


        /// <summary>
        /// 从模板导出excel
        /// </summary>
        /// <param name="templateFile">模板文件</param>
        /// <param name="table">数据表</param>
        /// <returns>excel流</returns>
        public static MemoryStream BuildExcelByTemplate(string templateFile, DataTable table)
        {
            int rowIndex = 0;
            int colIndex = 0;
            MemoryStream ms = new MemoryStream();

            FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read);//读入excel模板
            HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
            HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.GetSheet("Sheet1");
            foreach (DataRow row in table.Rows)
            {   //双循环写入table中的数据
                rowIndex++;
                colIndex = 0;
                var xlsrow = sheet1.GetRow(rowIndex);
                foreach (DataColumn col in table.Columns)
                {
                    if (xlsrow == null)
                    {
                        xlsrow = sheet1.CopyRow(rowIndex - 2, rowIndex);
                    }
                    xlsrow.GetCell(colIndex).SetCellValue(row[col.ColumnName].ToString());
                    colIndex++;
                }
            }

            sheet1.ForceFormulaRecalculation = false;
            hssfworkbook.Write(ms);
            file.Close();
            return ms;
        }

        #endregion

        #region 读取xls
        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ReadExcelDocument(string filePath, bool isFirstRowColumn = true, string sheetName = null)
        {
            IWorkbook workbook = null;
            FileStream fs = null;
            ISheet sheet = null;

            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                if (filePath.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (filePath.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (!string.IsNullOrEmpty(sheetName))
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                DataColumn column = new DataColumn(i.ToString());
                                data.Columns.Add(column);
                            }
                        }
                        startRow = sheet.FirstRowNum;
                    }
                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch
            {
                return null;
            }
        }

        public static DataTable ReadStreamDocument(Stream stream, string fileName, bool isFirstRowColumn = true, string sheetName = null)
        {
            IWorkbook workbook = null;
            ISheet sheet = null;

            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(stream);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(stream);

                if (!string.IsNullOrEmpty(sheetName))
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                DataColumn column = new DataColumn(i.ToString());
                                data.Columns.Add(column);
                            }
                        }
                        startRow = sheet.FirstRowNum;
                    }
                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch
            {
                return null;
            }
        }
        #endregion
    }
}
